package com.lianqi.emcpframework.dataaccess.configurer;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.lianqi.emcpframework.dataaccess.DataAccessContext;
import com.lianqi.emcpframework.dataaccess.DataAccessContextHolder;
import com.lianqi.emcpframework.dataaccess.internal.SimpleDataAccessContext;

/**
 * @program emcp-framework
 * @ClassName DataAccessArgumentResolver
 * @description: 权限上下文解析器
 * @author: sky
 * @create: 2018/11/30 20:37
 */
public class DataAccessArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == DataAccessContext.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
        NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) {
        String sessionId = nativeWebRequest.getNativeRequest(HttpServletRequest.class).getSession().getId();
        DataAccessContextHolder.bindCurrentContextId(sessionId);
        DataAccessContext context = DataAccessContextHolder.get();
        if (context != null && context instanceof SimpleDataAccessContext) {
            ((SimpleDataAccessContext)context).setContextId(sessionId);
        }
        DataAccessContextHolder.unbindCurrentContextId();
        return context;
    }
}
